package com.css.fxfzxczh.modules.fieldWorkManage.InvestigationGroupManage.service.impl;

import com.css.fxfzxczh.constants.YNEnum;
import com.css.fxfzxczh.modules.fieldWorkManage.InvestigationGroupManage.entity.InvestigationPersonnel;
import com.css.fxfzxczh.modules.fieldWorkManage.InvestigationGroupManage.entity.InvestigationTeam;
import com.css.fxfzxczh.modules.fieldWorkManage.InvestigationGroupManage.params.InvestigationParam;
import com.css.fxfzxczh.modules.fieldWorkManage.InvestigationGroupManage.params.PageParam;
import com.css.fxfzxczh.modules.fieldWorkManage.InvestigationGroupManage.repository.InvestigationGroupRepository;
import com.css.fxfzxczh.modules.fieldWorkManage.InvestigationGroupManage.service.InvestigationGroupService;
import com.css.fxfzxczh.modules.fieldWorkManage.InvestigationGroupManage.vo.InvestigationGroupVO;
import com.css.fxfzxczh.modules.fieldWorkManage.InvestigationGroupManage.vo.PersonnelVO;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.entity.EarEveManage;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.repository.EarEveManageRepository;
import com.css.fxfzxczh.modules.synthesizeInfoManage.personnelManagement.entity.PersonnelManagement;
import com.css.fxfzxczh.modules.synthesizeInfoManage.personnelManagement.repository.PersonnelManagementRepository;
import com.css.fxfzxczh.modules.synthesizeInfoManage.vehManage.entity.VehManage;
import com.css.fxfzxczh.modules.synthesizeInfoManage.vehManage.queryParams.VehManageQuaParams;
import com.css.fxfzxczh.modules.synthesizeInfoManage.vehManage.repository.VehManageRepository;
import com.css.fxfzxczh.util.*;
import com.css.fxfzxczh.web.PlatformSessionContext;
import com.css.fxfzxczh.zcpt.sys.entity.SUser;
import com.css.fxfzxczh.zcpt.sys.service.SUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: zhangSongRui
 * @CreateTime: 2023/01/15
 * @Description: 调查组
 */
@Service
@Slf4j
public class InvestigationGroupServiceImpl implements InvestigationGroupService {

    @Resource
    private InvestigationGroupRepository investigationGroupRepository;
    @Resource
    private PersonnelManagementRepository personnelManagementRepository;
    @Resource
    VehManageRepository vehManageRepository;

    @Resource
    SUserService sUserService;
    @Resource
    private RedisLockUtil redisLockUtil;

    @Autowired
    EarEveManageRepository earEveManageRepository;

    @Override
    public void save(InvestigationParam param) {
        InvestigationTeam investigationTeam = new InvestigationTeam();
        BeanUtils.copyProperties(param, investigationTeam);
        //调查组id
        String xitId = UUID.randomUUID().toString().replaceAll("-", "");
        investigationTeam.setXitId(xitId);
        investigationTeam.setDelFlag(YNEnum.N.toString());
        investigationTeam.setCreateUser(PlatformSessionContext.getUserID());
        investigationTeam.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        investigationGroupRepository.save(investigationTeam);
        List<InvestigationPersonnel> personnel = param.getPersonnel();
        List<InvestigationPersonnel> driver = param.getDriver();
        personnel.addAll(driver);
        //如果没有传组员信息则不用新增
        if (personnel.size() != 0) {
            //批量新增调查组人员
            for (InvestigationPersonnel investigationPersonnel : personnel) {
                investigationPersonnel.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                investigationPersonnel.setInvestigationId(xitId);
                investigationPersonnel.setDelFlag(YNEnum.N.toString());
                if (investigationPersonnel.getXpimId()!=null){
                    investigationPersonnel.setPersonnelId(investigationPersonnel.getPersonnelId());
                }else if (investigationPersonnel.getXvmId()!=null){
                    investigationPersonnel.setPersonnelId(investigationPersonnel.getPersonnelId());
                }
            }
            investigationGroupRepository.batchSavePersonnel(personnel);
        }
    }


    /**
     * 修改单条数据
     * @param param
     */
    @Override
    @Transactional(rollbackFor = Exception.class )
    public void update(InvestigationParam param) {
        InvestigationTeam investigationTeam = new InvestigationTeam();
        BeanUtils.copyProperties(param, investigationTeam);
        //删除该调查组下所有人员
        investigationGroupRepository.deleteInvestigationGroupPersonnel(param.getXitId());
        //更新调查组
        investigationTeam.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        investigationTeam.setUpdateUser(PlatformSessionContext.getUserID());
        investigationGroupRepository.update(investigationTeam);
        List<InvestigationPersonnel> personnel = param.getPersonnel();
        List<InvestigationPersonnel> driver = param.getDriver();
        personnel.addAll(driver);
        //如果没有传组员信息则不用新增
        if (personnel.size() != 0) {
            //批量新增调查组人员
            for (InvestigationPersonnel investigationPersonnel : personnel) {
                investigationPersonnel.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                investigationPersonnel.setInvestigationId(param.getXitId());
                investigationPersonnel.setDelFlag(YNEnum.N.toString());
                if (investigationPersonnel.getXpimId()==null){
                    investigationPersonnel.setPersonnelId(investigationPersonnel.getPersonnelId());
                }else {
                    investigationPersonnel.setPersonnelId(investigationPersonnel.getPersonnelId());
                }
            }
            investigationGroupRepository.batchSavePersonnel(personnel);
        }
    }

    @Override
    public List<InvestigationTeam> getInvGroupListByXsemId(String xsemId) {
        return investigationGroupRepository.getInvGroupListByXsemId(xsemId);
    }

    @Override
    public InvestigationTeam getHeadInfo(String xsemId) {
        InvestigationTeam obj = new InvestigationTeam();
        String user = sUserService.getSUser(PlatformSessionContext.getUserID());
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        //创建人
        obj.setCreateUser(sUser.getUserName());
        //创建时间
        obj.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        //创建人单位
        obj.setCompany(sUser.getOrgName());
        //调查组编号
        //获取当前地震事件
        EarEveManage earEveManage = earEveManageRepository.findById(xsemId);
        obj.setTeamCode(getCode(earEveManage.getEventCode()));
        return obj;
    }

    /**
     * 组员添加列表
     *
     * @return
     */
    @Override
    public Map<String, Object> getPersonnelList(PersonnelManagement queParams, int curPage, int pageSize) {
        Map<String, Object> page = personnelManagementRepository.getPage(queParams, curPage, pageSize);
        List<PersonnelManagement> list = (List<PersonnelManagement>) page.get("rows");
        ArrayList<PersonnelVO> personnelVOList = new ArrayList<>();
        //根据人员id获取所属组长和组长手机号
        for (PersonnelManagement personnelManagement : list) {
            PersonnelVO personnelVO = new PersonnelVO();
            List<InvestigationTeam> team = investigationGroupRepository.getPersonnelList(queParams.getXsemId(),personnelManagement.getUuid());
            StringBuilder leader = new StringBuilder();
            StringBuilder leaderPhone = new StringBuilder();
            for (int i = 0; i < team.size(); i++) {
                InvestigationTeam investigationTeam = team.get(i);
                if (i < team.size() - 1) {
                    leader.append(investigationTeam.getLeader()).append(",");
                    leaderPhone.append(investigationTeam.getLeaderPhone()).append(",");
                } else {
                    leader.append(investigationTeam.getLeader());
                    leaderPhone.append(investigationTeam.getLeaderPhone());
                }
            }
            BeanUtils.copyProperties(personnelManagement, personnelVO);
            personnelVO.setPersonName(personnelManagement.getPersonName());
            personnelVO.setXpimId(personnelManagement.getXpimId());
            personnelVO.setPersonnelId(personnelManagement.getUuid());
            //组长
            personnelVO.setLeader(leader.toString());
            //组长电话
            personnelVO.setLeaderPhone(leaderPhone.toString());
            personnelVOList.add(personnelVO);
        }
        page.put("rows", personnelVOList);
        return page;
    }

    /**
     * 司机添加列表
     * @param queParams
     * @param curPage
     * @param pageSize
     * @return
     */
    @Override
    public Map<String, Object> getDriverList(VehManageQuaParams queParams, int curPage, int pageSize) {
        Map<String,Object> page=vehManageRepository.getPage(queParams, curPage, pageSize);
        List<VehManage> list = (List<VehManage>) page.get("rows");
        ArrayList<PersonnelVO> personnelVOList = new ArrayList<>();
        //根据人员id获取所属组长和组长手机号
        for (VehManage vehManage : list) {
            PersonnelVO personnelVO = new PersonnelVO();
            List<InvestigationTeam> team = investigationGroupRepository.getPersonnelList(queParams.getXsemId(),vehManage.getDriverId());
            StringBuilder leader = new StringBuilder();
            StringBuilder leaderPhone = new StringBuilder();
            for (int i = 0; i < team.size(); i++) {
                InvestigationTeam investigationTeam = team.get(i);
                if (i < team.size() - 1) {
                    leader.append(investigationTeam.getLeader()).append(",");
                    leaderPhone.append(investigationTeam.getLeaderPhone()).append(",");
                } else {
                    leader.append(investigationTeam.getLeader());
                    leaderPhone.append(investigationTeam.getLeaderPhone());
                }
            }
            BeanUtils.copyProperties(vehManage, personnelVO);
            //因为车辆管理中获取不全司机信息所以通过司机id去人员管理中查询
            PersonnelManagement byId = personnelManagementRepository.findById(vehManage.getDriverId());
            personnelVO.setUnit(byId.getUnit());
            personnelVO.setGender(byId.getGender());
            personnelVO.setXvmId(vehManage.getDriverId());
            personnelVO.setPersonName(vehManage.getDriver());
            personnelVO.setPersonnelId(vehManage.getDriverId());
            //组长
            personnelVO.setLeader(leader.toString());
            //组长电话
            personnelVO.setLeaderPhone(leaderPhone.toString());
            personnelVOList.add(personnelVO);
        }
        page.put("rows",personnelVOList);
        return page;
    }

    //根据id查询
    @Override
    public InvestigationGroupVO findById(String id) {
        InvestigationGroupVO investigationGroupVO = new InvestigationGroupVO();
        //根据id查询调查组信息
        InvestigationTeam team = investigationGroupRepository.findById(id);
        BeanUtils.copyProperties(team, investigationGroupVO);
        //获取组员
        List<PersonnelVO> personnel = investigationGroupRepository.queryPersonnel(team.getXitId());
        //获取司机
        List<PersonnelVO> driver = investigationGroupRepository.querydriver(team.getXitId());
        investigationGroupVO.setPersonnel(personnel);
        investigationGroupVO.setDriver(driver);
        return investigationGroupVO;
    }

    //根据id保存组员
    @Override
    public void savePersonnel(InvestigationPersonnel investigationPersonnel) {
        //id
        investigationPersonnel.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        investigationPersonnel.setDelFlag(YNEnum.N.toString());
        investigationPersonnel.setCreateUser(PlatformSessionContext.getUserID());
        investigationPersonnel.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        investigationGroupRepository.savePersonnel(investigationPersonnel);
    }

    //根据id删除组员
    @Override
    public void deletePersonnel(String id) {
        investigationGroupRepository.deletePersonnel(id);
    }

    //根据id删除调查组,同时直接删除调查组下面的所有人员
    @Override
    public void deleteInvestigationGroup(String id) {
        investigationGroupRepository.deleteInvestigationGroup(id);
        investigationGroupRepository.deleteInvestigationGroupPersonnel(id);
    }

    @Override
    public Map<String, Object> getPage(PageParam queParams, int curPage, int pageSize) {
        String user = sUserService.getSUser(PlatformSessionContext.getUserID());
        String userName = CreateGson.createGson().fromJson(user, SUser.class).getUserName();
        Map<String, Object> page = investigationGroupRepository.getPage(queParams, curPage, pageSize);
        List<InvestigationTeam> list = (List<InvestigationTeam>) page.get("rows");
        ArrayList<InvestigationGroupVO> voList = new ArrayList<>();
        for (InvestigationTeam team : list) {
            InvestigationGroupVO investigationGroupVO = new InvestigationGroupVO();
            BeanUtils.copyProperties(team, investigationGroupVO);
            //获取组员
            List<PersonnelVO> personnel = investigationGroupRepository.queryPersonnel(team.getXitId());
            //获取司机
            List<PersonnelVO> driver = investigationGroupRepository.querydriver(team.getXitId());
            investigationGroupVO.setPersonnel(personnel);
            investigationGroupVO.setDriver(driver);
            investigationGroupVO.setCreateUserName(userName);
            voList.add(investigationGroupVO);
        }
        page.put("rows",voList);
        return page;
    }

    //获取调查组编号
    public String getCode(String eventCode) {
        String requestId = UUIDGenerator.getUUID();
        String code = "";
        Boolean isLocked = redisLockUtil.lock("redis_eventCode_lock_serialNum", requestId, 6L);
        if (isLocked){
            log.info("成功获取redis_eventCode_lock_serialNum锁");
            StringBuilder samPoiCode = new StringBuilder(eventCode+"DCZ");
            //日期两位
            String strDay = new SimpleDateFormat("dd").format(new Date());
            DecimalFormat decimalFormat=new DecimalFormat("00");
            String num="";
            String maxNum=investigationGroupRepository.getMaxNum(samPoiCode.append(strDay).toString());
            System.out.println("--------------"+ maxNum);
            if(PlatformObjectUtils.isEmpty(maxNum)){
                int i = 1;
                num=decimalFormat.format(i);
            }else{
                System.out.println("--------------"+ maxNum);
                String substring = maxNum.substring(maxNum.length() - 2);
                num = decimalFormat.format(Integer.parseInt(substring) + 1);
            }
            redisLockUtil.releaseLock("redis_distributed_lock_serialNum", requestId);
            log.info("成功释放redis_distributed_lock_serialNum锁");
            code = samPoiCode.append(num).toString();
        }else {
            log.info("获取redis_eventCode_lock_serialNum锁失败，进行休眠");
            try {
                Thread.sleep(10000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return code;
    }

    /****
     * 从哪里开始计数 比如startValue=2，则会从003,004,005等
     * @param startValue
     * @return
     */
    public String getNext(String startValue) {
        Integer i = Integer.valueOf(startValue);
        String format = String.format("%02d", i + 1);
        return format;
    }
}
